package com.gitee.melin.bee.core.hibernate5.validation;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorContext;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class ConstValidator implements ConstraintValidator<ValidConst, CharSequence> {

    private String[] values;

    @Override
    public void initialize(ValidConst validConst) {
        values = validConst.value();
    }

    @Override
    public boolean isValid(CharSequence value, ConstraintValidatorContext context) {
        if (value == null) {
            return false;
        }

        if (context instanceof HibernateConstraintValidatorContext) {
            context.unwrap( HibernateConstraintValidatorContext.class ).
                    addMessageParameter( "values", StringUtils.join(values, ","));
        }

        return ArrayUtils.contains(values, value);
    }
}
